import React, { useRef, useEffect,useState } from 'react';  
import { Modal, Button,Input, List, Avatar, Badge ,message as antMessage} from 'antd';  
import { useHistory } from 'react-router-dom/cjs/react-router-dom.min';
const { TextArea } = Input;
// 列表数据
const data=[
  {
    title:'用户1',
    id:'1',
    description:'你好，在吗？',
    count:2 ,
    messages:[]
  },
  {
    title:'用户2',
    id:'2',
    description:'啊',
    count:1,
    messages:[]
  },
  {
    title:'用户3',
    id:'3',
    description:'大苏打阿松？',
    count:0,
    messages:[]
  }
]


  
const UserMessage = () => { 
  const history = useHistory()
  const handleAvatar = (userId)=>{
    history.push('/other')
  }
  // 发送信息
  const [show, setShow] = useState(false);  
  const [activeUser, setActiveUser] = useState(null); 
  const [inputValue, setInputValue] = useState('');  
  const messagesEndRef = useRef(null)
  // 发送消息不能为空
  const handleClose = () => {  
    setShow(false);  
    setInputValue('');  
  };  
  const handleSend = () => { 
    if(!inputValue.trim()){
      antMessage.warning('不能发送空消息')
      return
    } 
    // 发送消息头像在右，并且存有消息记录
    const newMessages = [...activeUser.messages, { sender: '我', message: inputValue }]; 
    const userIndex = data.findIndex(user => user.id === activeUser.id);
    data[userIndex].messages = newMessages;
    setActiveUser({...activeUser,messages:newMessages})  
    setInputValue('');  
  };  

  // 用户聊天名
  const showModal= (user)=>{
    setShow(true)
    setActiveUser(user)
  }
  const handleOk =()=>{
    setShow(false)
  }
  // 滚动栏随着消息滚动
  useEffect(() => {
    if (messagesEndRef.current) {
      messagesEndRef.current.scrollIntoView({ behavior: 'smooth' });
    }
  }, [activeUser]);

  
  return (  
    <div>  
      {/* 聊天框 */}
      <Modal  
        title={activeUser?.title}  
        open={show}  
        onCancel={handleClose}  
        onOk={handleOk}
        footer={null}  
      >  
        <div style={{
            marginTop: 20,
            height:350,
            overflow:'auto'
        }}
        >  
          {activeUser?.messages.map((message, index) => (  
            <div key={index}
            style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: '10px' }}>  
             <div style={{ maxWidth: '70%', wordWrap: 'break-word', backgroundColor: 'white', padding: '10px', borderRadius: '10px', boxShadow: '0px 0px 10px rgba(0,0,0,0.15)' }}>
                {message.message}
              </div>
              <Avatar style={{ marginLeft: '10px' }}>U</Avatar>
            </div>  
          ))}  
          <div ref={messagesEndRef} />
        </div>  
        <TextArea  
          autoSize={{ minRows: 1, maxRows: 3 }}
          value={inputValue}  
          onChange={(e) => setInputValue(e.target.value)}  
          placeholder="Type a message..."  
          style={{ marginTop: 20,width:'80%'}} 
          
        />  
        <Button onClick={handleSend}>Send</Button>  
      </Modal>  
          

      {/* 列表 */}
      <div style={{display:'flex'}}>
      <List
        style={{
          width:"100vh",
          margin:'auto'
        }}
        itemLayout='horizontal'
        dataSource={data}
        rowKey={data.id}
        renderItem={(item,index)=>{
          
          return(
          <List.Item key={item.id} onClick={()=> showModal(item)}>
            <List.Item.Meta
              avatar={<Avatar onClick={()=>handleAvatar(item.id)} src={`https://xsgames.co/randomusers/avatar.php?g=pixel&key=${index}`} />}
              title={<Badge 
                count={item.count}
                offset={[20]}
                color='#52c41a'>
                  {item.title}
              </Badge>}
              description={item.description}
              // onClick={() => setShow(true)} 
            >
             
            </List.Item.Meta>
          </List.Item>
        )}}
      >

      </List>
      </div>

    </div>  
  );  
};

export default UserMessage